package com.walala.dispatcher.server;

import java.net.InetAddress;
import java.util.concurrent.Executors;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.walala.dispatcher.handler.UdpServerHandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioDatagramChannel;
import io.netty.handler.codec.json.JsonObjectDecoder;

public class UdpServer {

	private static Logger logger = LoggerFactory.getLogger(UdpServer.class);
	
	private static Channel channel;
	
	public static void init(String ip, int port){
		
		final NioEventLoopGroup group = new NioEventLoopGroup();
		
		try {
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioDatagramChannel.class)
				.option(ChannelOption.SO_BROADCAST, true)
				.handler(new ChannelInitializer<NioDatagramChannel>() {
			        @Override
			        public void initChannel(NioDatagramChannel ch) throws Exception {
			            ChannelPipeline p = ch.pipeline();
			            p.addLast("decoder", new JsonObjectDecoder());
			            p.addLast(new UdpServerHandler());
			        }
			    });
			
			//InetAddress address = InetAddress.getLocalHost();
			InetAddress address = InetAddress.getByName(ip);
			channel = b.bind(address, port).sync().channel();
			Executors.newSingleThreadExecutor().execute(new Runnable() {
			    @Override
			    public void run() {
			        try {
			            channel.closeFuture().sync();
			        } catch (InterruptedException e) {
			            logger.error("udp server closeFuture error",e);
			        } finally {
			            group.shutdownGracefully();
			        }
			    }
			});
			logger.info("udp server started,host:[{}],port:[{}]",ip,port);
		} catch (Exception e) {
			logger.error("start udp server occoured an error",e);
		}
	}
	
}
